package com.orange.adminapi.controller.coupon;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orange.core.pojo.PageReqDto;
import com.orange.core.pojo.R;
import com.orange.core.pojo.entity.coupon.Coupon;
import com.orange.core.pojo.req.coupon.CouponPageReq;
import com.orange.core.pojo.req.coupon.CouponStockUpdateReq;
import com.orange.core.service.coupon.CouponService;
import com.orange.core.validator.group.Update;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 优惠券
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/coupon")
public class CouponController {

    private final CouponService couponService;

    /**
     * 查询
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).COUPON_LIST.permission.identifier)")
    @PostMapping("/page")
    public R<Page<Coupon>> page(@RequestBody PageReqDto<CouponPageReq> req) {
        return R.ok(couponService.page(req));
    }

    /**
     * 新增
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).COUPON_SAVE.permission.identifier)")
    @PostMapping
    public R<Boolean> save(@RequestBody @Validated Coupon coupon) {
        return R.ok(couponService.save(coupon.withId(null)));
    }

    /**
     * 编辑
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).COUPON_UPDATE.permission.identifier)")
    @PutMapping
    public R<Boolean> update(@RequestBody @Validated(Update.class) Coupon coupon) {
        return R.ok(couponService.updateById(coupon));
    }

    /**
     * 删除
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).COUPON_DELETE.permission.identifier)")
    @DeleteMapping("/{id}")
    public R<Boolean> del(@PathVariable int id) {
        return R.ok(couponService.removeById(id));
    }

    /**
     * 上下架
     *
     * @param shelf 上架状态：1上架，0下架
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).COUPON_SHELF.permission.identifier)")
    @PostMapping("/shelf/{id}/{shelf}")
    public R<Boolean> shelf(@PathVariable int id, @PathVariable("shelf") int shelf) {
        return R.ok(couponService.shelf(id, shelf));
    }

    /**
     * 修改库存
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).COUPON_STOCK.permission.identifier)")
    @PostMapping("/stock/{id}")
    public R<Boolean> stock(@PathVariable int id, @RequestBody CouponStockUpdateReq req) {
        return R.ok(couponService.changeStock(id, req.getStock()));
    }
}
